package com.lmx.messagetemplate.ui.activity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lmx.messagetemplate.R;
import com.lmx.messagetemplate.bean.Message;
import com.lmx.messagetemplate.bean.MessageTemplate;
import com.lmx.messagetemplate.ui.adapter.MessageAdapterRv;

import java.util.List;

public class MessageActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private MessageAdapterRv adapterRv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);
        initView();
        initEvent();
        getData();
    }

    private void initView() {
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        recyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        adapterRv = new MessageAdapterRv(this);
        recyclerView.setAdapter(adapterRv);
    }

    private void initEvent() {
        adapterRv.setOnItemClickListener((v, data) -> {
            copyToClipboard(data.getResult());
        });
    }

    private void getData() {
        MessageTemplate template = (MessageTemplate) getIntent().getSerializableExtra("data");
        List<Message> data = template.getData();
        adapterRv.setData(data);
    }

    private void copyToClipboard(String content) {
        try {
            ClipboardManager manager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clipData = ClipData.newPlainText("label", content);
            manager.setPrimaryClip(clipData);
            Toast.makeText(this, "复制成功！", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(this, "复制失败！\n错误信息：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
}